<template>
  <div id="default-dialog"
    v-loading="loading"
    element-loading-text="加载中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(255, 255, 255, 0.7)"
  >
    <el-form
      ref="form"
      :model="form"
      label-width="80px"
      label-position="top"
      @submit.native.prevent
    >
      <el-form-item label="关键词:">
        <div class="search">
          <el-input
            @clear="handleInquire"
            clearable
            v-model="form.input"
            show-word-limit
            maxlength="100"
            class="input"
            placeholder="请输入要对比的法规关键词"
            @keyup.enter.native="handleInquire(false)"
          >
            <el-button
              type="primary"
              class="inquire"
              @click="handleInquire(false)"
              slot="append"
            >查询</el-button>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="相关法规:">
        <div ref="elScrollbar" class="laws-checkbox-item">
          <el-checkbox-group v-model="form.lawList" @change="handleCheckbox" :max="6">
            <el-checkbox
              :label="v.id"
              v-for="(v,i) in lawList"
              :key="v.id"
              :title="v.title"
              :checked="v.checked"
              :disabled="defaultCheckLaw.id === v.id"
              :class="i?'':'defaultChecked'"
            >{{v.title}}</el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="line"></div>
      </el-form-item>
      <el-form-item>
        <div class="scrollbar">
          <div v-for="(v, i) in checkLawsGather" :key="i" class="laws-check-item">
            <span :title="v.title">{{v.title}}</span>
            <i class="el-icon-circle-close" @click="delCheckLaw(v, i)" v-if="i!==0"></i>
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import _ from 'lodash'
export default {
  components: {},
  filters: {},
  props: {},
  data () {
    return {
      form: {
        input: '',
        lawList: []
      },
      lawList: [],
      loading: false,
      page: 1,
      page_size: 10,
      scrollTimeoutId: -1,
      defaultCheckLaw: null, // 默认选中
      flag: true, // 搜索法规时判断是否需要插入默认展示的法规
      checkLawsGather: [], // 选中法规的集合
      regulationsContrastFilters: null, // 法规对比列表的filter
      loadMore: 'more'
    }
  },
  computed: {
    // checkLawsGather () {
    //   return this.lawList.filter(item => this.form.lawList.findIndex(innerItem => innerItem === item.id) !== -1)
    // }
  },
  watch: {
    'form.lawList': {
      handler (newValue, oldValue) {
        if (newValue.length > oldValue.length) {
          this.checkLawsGather.push(
            this.lawList.filter(
              item => item.id === this.getArrDifference(newValue, oldValue)[0]
            )[0]
          )
        } else if (newValue.length < oldValue.length) {
          this.checkLawsGather.splice(
            this.checkLawsGather.findIndex(
              item => item.id === this.getArrDifference(newValue, oldValue)[0]
            ),
            1
          )
        }
        this.$emit('checkboxChange', newValue)
      },
      deep: true
    }
  },
  created () {},
  mounted () {
    this.defaultCheckLaw = JSON.parse(
      sessionStorage.getItem('setDeafultCheckLaw')
    ) // 获取默认需要展示的法规
    this.regulationsContrastFilters = JSON.parse(
      sessionStorage.getItem('filterData')
    ) // 获取法规对比列表的filter参数
    // delete this.regulationsContrastFilters['keywords']
    this.handleInquire(false) // dialog默认展示法规对比列表的数据，只有进行搜索时才展示搜索结果
    let scrollView = this.$refs.elScrollbar
    scrollView.addEventListener('scroll', this.handleScroll)
  },
  activated () {},
  beforeDestroy () {},
  methods: {
    /**
     * 对form.lawList(多选框组发生改变时)做diff比较出两个数组发生改变的值
     * @param newValue
     * @param oldValue
     * @returns {Uint8Array}
     */
    getArrDifference (newValue, oldValue) {
      return newValue.concat(oldValue).filter(function (v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v)
      })
    },
    handleScroll (e) {
      if (this.scrollTimeoutId !== -1 || this.loadMore === 'none') {
        return false
      }
      let targetHeight = e.target.offsetHeight
      let childHeight = e.target.scrollHeight
      let targetScrollTop = e.target.scrollTop
      if (targetScrollTop >= childHeight - targetHeight - 10) {
        // 发起请求
        this.page++
        this.handleInquire(true)
      } else {
        return false
      }
      this.scrollTimeoutId = setTimeout(() => {
        clearTimeout(this.scrollTimeoutId)
        this.scrollTimeoutId = -1
      }, 200)
    },
    handleInquire (pullOnLoading) {
      // 请求dialog搜索出来的数据
      if (!pullOnLoading) {
        this.page = 1
      }
      this.regulationsContrastFilters.keywords2 = this.form.input
      this.regulationsContrastFilters.page = this.page
      this.regulationsContrastFilters.page_size = this.page_size
      this.loading = true
      this.$api
        .getLawsList(this.regulationsContrastFilters)
        .then(res => {
          // if (res.data.data.length < 10) {
          //   this.$msgMnger.warn('没有更多数据了')
          // }
          // 给所有的多选框加选中状态
          for (const key in res.data.data) {
            if (res.data.data.hasOwnProperty(key)) {
              this.$set(res.data.data[key], 'checked', false)
            }
          }
          // 删除请求过来的数据里和点击法规对比那一列重复的数据
          if (res.data.data.length >= 1) {
            res.data.data.forEach((item, index) => {
              if (item.id === this.defaultCheckLaw.id) {
                res.data.data.splice(index, 1)
              }
            })
          }
          // if (!this.zoneBit) {
          //   // 默认展示法规列表的选中的数据
          //   this.$set(res.data.data, 0, this.defaultCheckLaw)
          //   // 标志位
          //   this.zoneBit = true
          // }
          // 判断是搜索还是上拉加载，如果是搜索就覆盖，如果是上拉加载就进行尾插
          if (pullOnLoading) {
            this.lawList.push(...res.data.data)
          } else {
            res.data.data.unshift(this.defaultCheckLaw)
            this.lawList = res.data.data
            // 在搜索的时候在选中法规集合里添加默认法规
            if (this.flag) {
              this.checkLawsGather.push(res.data.data[0])
              this.flag = false
            }
          }
          if (res.data.data.length === 0) {
            this.loadMore = 'none'
          } else {
            this.loadMore = 'more'
          }
          this.loading = false
        })
        .catch(err => {
          console.log(err)
          this.loading = false
          this.$msgMnger.httpError(err)
        })
    },
    delCheckLaw (value) {
      // 删除多选框组绑定的id集合
      this.form.lawList.forEach((v, i) => {
        if (this.form.lawList[i] === value.id) {
          this.form.lawList.splice(i, 1)
        }
      })
      // 删除选中法规集合
      this.checkLawsGather = this.checkLawsGather.filter(
        item => item.id !== value.id
      )
    },
    handleCheckbox (val) {}
  }
}
</script>

<style lang="scss" scoped>

#default-dialog {
  padding-left: 88px;
  .search {
    .input {
      width: 550px;
    }
    .inquire {
      // margin-top: -1px;
      border-radius: 0 !important;
    }
  }
  .scrollbar {
    height: auto;
    overflow-y: auto;
  }
  .laws-check-item {
    span {
      width: 525px;
      display: inline-block;
      overflow: hidden;
      color: $default-text-color;
      text-overflow: ellipsis;
      white-space: nowrap;
      vertical-align: middle;
      font-weight: 600;
    }
    > i {
      font-size: 20px;
      color: rgb(145, 145, 145);
      vertical-align: middle;
      margin-left: 5px;
      cursor: pointer;
      &:hover {
        color: $primary-color;
      }
    }
  }
  .laws-checkbox-item {
    height: calc(100vh - 700px);
    min-height: 200px;
    overflow-y: auto;
  }
  .line {
    width: 540px;
    border-bottom: 1px solid #d9d9d9;
    margin: 22px 0 5px 0;
  }
}
</style>

<style lang="scss">

#default-dialog {
  .search{
    .el-input__inner{
      padding-right: 75px !important;
    }
  }
  .el-checkbox {
    display: block;
  }
  .el-checkbox:first-of-type {
    .el-checkbox__label {
      color: $primary-color;
    }
  }
  .el-scrollbar {
    height: 100%;
  }
  .el-form-item {
    margin-bottom: 0;
    .el-form-item__label {
      color: $default-text-color;
      padding-bottom: 0;
      font-size: $fs-m;
    }
  }
  .el-form-item:last-of-type {
    margin-bottom: 25px;
  }
  .el-input-group__append {
    background-color: $primary-color !important;
    color: white;
  }
  .el-checkbox__label {
    width: 480px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
  }
}
</style>
